package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Override
    public Result follow(String id, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        if (isFollow) {
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(Long.valueOf(id));
            boolean save = save(follow);
            if (BooleanUtil.isTrue(save)) {
                stringRedisTemplate.opsForSet().add(key, id);
            }
        } else {
            LambdaQueryWrapper<Follow> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            objectLambdaQueryWrapper.eq(Follow::getUserId, userId)
                    .eq(Follow::getFollowUserId, id);
            boolean remove = remove(objectLambdaQueryWrapper);
            if (BooleanUtil.isTrue(remove)) {
                stringRedisTemplate.opsForSet().remove(key, id);
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(String id) {
        Long userId = UserHolder.getUser().getId();
        long count = count(lambdaQuery().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, id));
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(String id) {
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        String key2 = "follows:" + id;

        Set<String> strings = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (strings == null || strings.isEmpty()) {
            return Result.ok(strings);
        }
        List<Long> collect = strings.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> list = userService.listByIds(collect).stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(list);
    }
}
